package edu.zut.main.thread;

public class ThreadCommunication {
    public static void main(String[] args) {
        StoreHouse storeHouse = new StoreHouse();
        //生产者
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                char c = (char) (Math.random()*26+'a');
                storeHouse.deposit(c);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者").start();

        //消费者
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                storeHouse.get();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者").start();
    }
}

//仓库
class StoreHouse{
    private char[] data =new char[5];
    private int number = 0;
    //存
    public synchronized void deposit(char c){
        while (number == data.length){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        data[number] = c;
        System.out.println("生产了"+data[number]);
        number++;
    }
    //取
    public synchronized void get(){
        while (number == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notifyAll();
        number--;
        System.out.println("消费了"+data[number]);
    }
}
